﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Simple.Tools
{
   /// <summary>
   /// 转换为树的扩展
   /// </summary>
    public static class ConvertTreeExtension
    {
        /// <summary>
        /// 转化树结构扩展方法
        /// </summary>
        /// <typeparam name="TData"></typeparam>
        /// <typeparam name="TKey"></typeparam>
        /// <param name="trees"></param>
        /// <returns></returns>
        public static List<TData> ConvertTree<TData,TKey>(this List<TData> trees) where TData : ITree<TData, TKey>
        {
            if (SimpleCheck.IsNullOrEmpty(trees))
            {
                return null;
            }
            List<TData> roots = trees.Where(t =>t.IsRoot()).ToList();
            if (SimpleCheck.IsNullOrEmpty(roots))
            {
               var RootID=trees.Min(t => t.ParentId);
               roots = trees.Where(t =>t.ParentId.Equals(RootID)).ToList();
            }
            trees = trees.Where(t => !roots.Contains(t) && !t.IsRoot()).ToList();
            foreach (TData root in roots)
            {
                ConvertTree<TData,TKey>(root, trees);
            }
            return roots;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="TData"></typeparam>
        /// <typeparam name="TKey"></typeparam>
        /// <param name="root"></param>
        /// <param name="trees"></param>
        private static void ConvertTree<TData,TKey>(TData root, List<TData> trees) where TData : ITree<TData,TKey>
        {
            if(SimpleCheck.IsNullOrEmpty(trees))
            {
                return;
            }

            if (trees.Where(t=>t.ParentId.Equals(root.Id)).Any())
            {
                List<TData> Children = trees.Where(t=>t.ParentId.Equals(root.Id)).ToList();
                trees = trees.Where(t=>!t.ParentId.Equals(root.Id)).ToList();
                if (SimpleCheck.IsNullOrEmpty(root.Children))
                {
                    root.Children=new List<TData>();
                }
                root.Children.AddRange(Children);
                foreach (TData child in Children)
                {
                    ConvertTree<TData,TKey>(child,trees);
                }
            }
        }

    

    }
}
